<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\admin\controller;

use \think\Db;
use \think\Cookie;
use app\admin\model\Coupon as Cp;
use app\admin\model\Coupondetails as Cppt;
use think\log;

class Coupon extends User
{

    /**
     * 获取小数点位数
     */
    private function _getFloatLength($num)
    {
        $count = 0;
        $temp = explode('.', $num);

        if (sizeof($temp) > 1) {
            $decimal = end($temp);
            $count = strlen($decimal);
        }

        return $count;
    }

    /**
     * 列表首页
     */
    public function index()
    {
        $model=new Cp();
        $where='';
        $post= request()->post();
        //分页bug处理
        $temp_page=request()->param('page');
        if(isset($temp_page)){
            //条件从缓存取出
            $post=Cookie::get('postlist');
        }else{
            //把条件写入缓存
            Cookie::set('postlist',$post);
        }
        if (isset($post['coupon_types']) and $post['coupon_types'] > 0) {
            $where['coupon_types'] = $post['coupon_types'];
        }
        if (isset($post['coupon_status']) and $post['coupon_status'] > 0) {
            $where['coupon_status'] = $post['coupon_status'];
        }
        if (isset($post['coupon_name']) and !empty($post['coupon_name'])) {
            $where['coupon_name'] = ['like', '%' . $post['coupon_name'] . '%'];
        }
        $date= $model->where($where)->order('creattime desc')->paginate(20);

        foreach ($date as $key=>$va){
            $date[$key]['name']='';
            if ($va['coupon_userange']=='999999' || $va['classify_id']=='999999'){
                $date[$key]['name']='全部';
                continue;
            }
            if($va['coupon_model']==1){

                $id_temp=explode(',',$va['classify_id']);
                if(count($id_temp)>0){
                    $name='';
                    foreach ($id_temp as $l){
                        if($l==304){
                            $name_temp = '接送机';
                        }elseif($l==305){
                            $name_temp = '包车';
                        }else{
                            $name_temp=Db::name('classify')->where(['classify_id'=>$l])->find()['classify_name'];
                        }
                        if(empty($name)){
                            $name=$name_temp;
                        }else{
                            $name=$name.','.$name_temp;
                        }
                    }
                    $date[$key]['name']=$name;
                }else{
                    $date[$key]['name']='无';
                }
            }else{

                $id= explode(',',$va['coupon_userange']);

                if (!empty($id[0])){
                    $l=count($id);
                    for ($i=0;$i<$l;$i++){

                        $x=db('goods')->where('goods_id',$id[$i])->field('goods_name as name')->find();
                        if($date[$key]['name']){
                            $date[$key]['name'].=','.$x['name'];
                        }else{
                            $date[$key]['name'].=$x['name'];
                        }
                    };
                }else{
                    $date[$key]['name']='无';
                }

            }
        }


        $this->assign('lie',$date);
        $this->assign('wherelist',$post);
        return $this->fetch();
    }

    //添加优惠券
    public function addcoupon()
    {
        $log=[];
        if (request()->isAjax()){
            $adminid = Cookie::get('admin');
            $shu=  request()->post();

            if($shu['coupon_model'] == 2){
                $shu['classify_id']='';
                if(empty($shu['coupon_userange'])){
                    return $this->error('提交失败：商品必选');
                }
            }else if ($shu['coupon_model'] == 1){
                $shu['coupon_userange']='';
                if(empty($shu['classify_id'])){
                    return $this->error('提交失败：品类必选');
                }
            }

            $zhe=$shu['coupon_discount'.$shu['coupon_types']];
            $zhelength=$this->_getFloatLength($zhe);

            //判断折扣
            if ($shu['coupon_types']=='1'){
                $zhelength=$this->_getFloatLength($zhe);
                if ($zhe<0||$zhe>1||$zhelength>2){
                    return $this->error('提交失败：折扣率输入有误');
                }
            }
            //判断满减
            if ($shu['coupon_types']=='2'){
                if ($zhe<0||$zhelength>2){
                    return $this->error('提交失败：满减金额有误');
                }
            }
            //判断数量
            $shuliang=$this->_getFloatLength($shu['coupon_quantity']);
            if ($shu['coupon_quantity']<0||$shuliang>0){
                return $this->error('提交失败：数量输入有误');
            }

            //判断使用条件

            //判断领取限制
            if ($shu['receive_limit']<0||$this->_getFloatLength($shu['receive_limit'])>0){
                return $this->error('提交失败：限制领取输入有误');
            }

            //判断时间
            if($shu['poitype_time_rece'] ==1 || $shu['poitype_time_use'] ==3 ){
                $end_receivetime=4070880000;
            }else{
                $end_receivetime=strtotime($shu['end_receivetime'])+86399;
            }
            if($shu['poitype_time_use'] ==1 || $shu['poitype_time_use'] ==3  ){
                $end_usetime=4070880000;
            }else{
                $end_usetime=strtotime($shu['end_usetime'])+86399;
            }

            $date=[
                "coupon_userange"   =>  $shu['coupon_userange'],
                "coupon_types"      =>  $shu['coupon_types'],
                "coupon_discount"   =>  $shu['coupon_discount'.$shu['coupon_types']],
                "coupon_quantity"   =>  $shu['coupon_quantity'],
                "receive_limit"     =>  $shu['receive_limit'],
                "etart_receivetime" =>  strtotime($shu['etart_receivetime']),
                "end_receivetime"   =>  $end_receivetime,
                "etart_usetime"     =>  strtotime($shu['etart_usetime']),
                "end_usetime"       =>  $end_usetime,
                'creattime'         =>  time(),
                'admin_id'          =>  $adminid,
                'coupon_name'       =>  $shu['coupon_name'],
                //增加是否公开 限制类型  品类限制id
                'open_status'       =>  $shu['open_status'],
                'classify_id'       =>  $shu['classify_id'],
                'coupon_model'      =>  $shu['coupon_model'],
                'num_types'         =>  $shu['num_types'],
                'time_rece_type'    =>  $shu['poitype_time_rece'],
                'time_use_type'     =>  $shu['poitype_time_use'],
                'end_useday'        =>  !empty($shu['end_useday'])?$shu['end_useday']:'',
            ];


            if (!isset($shu['mjje'])){
                $date['coupon_usecondition']='0';
            }else{
                if ($shu['mjje']<0||$this->_getFloatLength($shu['mjje'])>2){
                    return $this->error('提交失败：使用条件输入有误');
                }

                $date['coupon_usecondition']=$shu['mjje'];

            }

            if ($date['etart_receivetime']>$date['end_receivetime']){
                return $this->error('提交失败：领取时间输入有误');
            }

            if ($date['etart_usetime']>$date['end_usetime']){
                return $this->error('提交失败：使用时间输入有误');
            }

            if($shu['poitype_time_rece'] == 2 && $shu['poitype_time_use'] == 2){
                //判断领取时间
                if ($date['etart_receivetime']>$date['end_receivetime']||$date['end_receivetime']<time()||$date['etart_receivetime']>$date['end_usetime']){
                    return $this->error('提交失败：领取时间输入有误');

                }
                //判断使用时间
                if ($date['etart_usetime']>$date['end_usetime']||$date['end_usetime']<time()||$date['etart_usetime']<$date['etart_receivetime']){
                    return $this->error('提交失败：使用时间输入有误');
                }
            }

            //判断状态
            if ($date['etart_receivetime']<time() || $shu['poitype_time_rece'] == 1){
                $date['coupon_status']='2';
            }else{
                $date['coupon_status']='1';
            }

            if (!empty($shu['coupon_id'])){
                //修改操作
                $k= db('coupon')->where('coupon_id',$shu['coupon_id'])->update($date);
                if ($k==true){
                    $log[]=[
                        '优惠券修改操作数据' => $date,
                        '优惠券id' => $shu['coupon_id'],
                    ] ;
                    Log::record($log);
                    return $this -> success( '修改成功');
                }else{
                    return $this -> error( '修改失败');
                }
            }else{
                //添加操作
                $k = db('coupon')->insert($date);
                if ($k==true){
                    $log[]=[
                        '优惠券新增操作数据' => $date,
                    ];
                    Log::record($log);
                    return $this -> success( '添加成功');
                }else{
                    return $this -> error( '添加失败');
                }
            }
        }else{
            $trip = Db::name('goods')->field('goods_name as name,goods_id as id')->limit(20)->select();
            $type=Db::name('classify')->select();
            $type[] = [
                "classify_id" => 304,
                "classify_name" => '接送机'
            ];
            $type[] = [
                "classify_id" => 305,
                "classify_name" => '包车'
            ];

            $this->assign('type',$type);
            $this->assign('trip',$trip);
            return $this->fetch();
        }
    }

    public function searchGoodsByName($name)
    {
        if(empty($name)){
            $list = db('goods')->field('goods_name as name,goods_id as id')->limit(20)->select();
        }else{
            $where['goods_name'] = ['like','%'.$name.'%'];
            $list = db('goods')->field('goods_name as name,goods_id as id')->where($where)->select();
        }

        $this->success('success','',$list);
    }
    //删除优惠券
    public function delcoupon(){
        if (request()->isAjax()){
            $id=input('id');
            if (empty($id)){
                return $this->error('数据不存在');
            }
            $model=new  Cp();
            $del= $model->where('coupon_id',$id)->delete();
            if ($del==false){
                return $this->error('删除失败');
            }else{
                return $this->success('删除成功');
            }
        }
    }

    //编辑
    public function edit(){
        $id = input('id');
        $model = new Cp();
        $date  = $model->where('coupon_id',$id)->find();

        $do  = [];//用于接收品类
        $do1 = [];//用于接收商品

        if($date['coupon_model'] == 1){
            $classify_id1=explode(',',$date['classify_id']);
            foreach ($classify_id1 as $v){
                if($v==304){
                    $do[] = ['id'=>$v,'name'=>'接送机'];
                }elseif($v==305){
                    $do[] = ['id'=>$v,'name'=>'包车'];
                }else{
                    $do[] = db('classify')->where('classify_id',$v)->field('classify_id as id,classify_name as name')->find();
                }
            }
        }else if($date['coupon_model'] == 2) {
            $classify_id1 = explode(',', $date['coupon_userange']);
            foreach ($classify_id1 as $v) {
                $do1[] = db('goods')->where('goods_id', $v)->field('goods_id as id,goods_name as name')->find();
            }
        }

        $date['classify_id1'] = $do;//品类
        $date['classify_id2'] = $do1;//商品

        if($date['coupon_model']==2 && $date['coupon_userange']!='999999'){
            $trip = Db::name('goods')->field('goods_name as name,goods_id as id')->where(['goods_id'=>['in',$date['coupon_userange']]])->select();
        }else{
            $trip = Db::name('goods')->field('goods_name as name,goods_id as id')->limit(20)->select();
        }

        $type = Db::name('classify')->select();
        $type[] = [
            "classify_id" => 304,
            "classify_name" => '接送机'
        ];
        $type[] = [
            "classify_id" => 305,
            "classify_name" => '包车'
        ];


        $this->assign('type' , $type);
        $this->assign('trip' , $trip);
        $this->assign('edit' , $date);

        return $this->fetch();
    }


    public function copy(){



        $trip = Db::name('goods')->field('goods_name as name,goods_id as id')->limit(20)->select();


        $sid=input('id');
        $model=new Cp();
        $date['name']='';
        $date=  $model->where('coupon_id',$sid)->find();

        if ($date['coupon_userange']=='999999' || $date['classify_id']=='999999'){
            $date['name']='全部';
        }else{

            $date['name']='';
            $id= explode(',',$date['coupon_userange']);

            //        $date['goods_id']='';
            if (!empty($id[0])){
                $l=count($id);
                for ($i=0;$i<$l;$i++){
                    $x=db('goods')->where('goods_id',$id[$i])->field('goods_name')->find();


                    if($date['name']){
                        $date['name'].=','.$x['goods_name'];
                        //                    $date['goods_id'].=','.$x['goods_id'];
                    }else{
                        $date['name'].=$x['goods_name'];
                        //                    $date['goods_id'].=$x['goods_id'];
                    }
                };

            }else{
                $date['name']='';
            }

        }




//        dump( $date['goods_id']);
        $this->assign('trip',$trip);
        $this->assign('edit',$date);
        return $this->fetch();

    }

    //停止
    public function stop(){
        if (request()->isAjax()){
            $id=input('id');
            if (!empty($id)){
                $date=db('coupon')->where('coupon_id',$id)->find();
                //未开始
                if ($date['coupon_status']=='1'){
                    if ($date['etart_receivetime']<time()&&$date['end_usetime']>time()){
                        $xg=db('coupon')->where('coupon_id',$id)->update([
                            'coupon_status'=>'2'
                        ]);
                        if ($xg==true){
                            return $this->success('活动开启成功');
                        }else{
                            return $this->error('活动开启失败');
                        }
                    }else{
                        if ($date['etart_receivetime']<time()&&$date['end_usetime']<time()){
                            return $this->error('活动已经结束了无法再次开启');
                        }
                        if ($date['etart_receivetime']>time()){
                            return $this->error('活动还没有到开启的时间呢');
                        }
                    }
                }else if ($date['coupon_status']=='2'){//
                    $xg =db('coupon')->where('coupon_id',$id)->update([
                        'coupon_status'=>'4'
                    ]);
                    if ($xg==true){
                        return $this->success('停止成功 可再次开启');
                    }else{
                        return $this->error('停止失败');
                    }
                }else if ($date['coupon_status']=='3'){
                    return $this->error('活动已结束');
                }else if ($date['coupon_status']=='4'){
                    if ($date['etart_receivetime']<time()&&$date['end_usetime']>time()){
                        $xg=db('coupon')->where('coupon_id',$id)->update([
                            'coupon_status'=>'2'
                        ]);
                        if ($xg==true){
                            return $this->success('活动开启成功');
                        }else{
                            return $this->error('活动开启失败');
                        }
                    }else{
                        if ($date['etart_receivetime']<time()&&$date['end_usetime']<time()){
                            $xg=db('coupon')->where('coupon_id',$id)->update([
                                'coupon_status'=>'3'
                            ]);

                            return $this->error('活动已经结束了无法再次开启');
                        }
                        if ($date['etart_receivetime']>time()){
                            return $this->error('活动还没有到开启的时间呢');
                        }
                    }
                }
            }else{
                return $this->error('参数错误！');
            }
        }
    }

    public function details()
    {
        if($this->request->isPost()){
            $id=$this->request->param('id');
            $usestatus=$this->request->param('usestatus');
            $where=['a.coupon_id'=>$id,'a.usestatus'=>$usestatus];
        }else{
            $id=  input('id');
            $where=request()->get();
            $where['a.coupon_id']=$id;
            unset($where['id']);
            unset($where['page']);
            $usestatus='';
        }
        if(isset($where['a.usestatus']) && $where['a.usestatus'] == ''){
            unset($where['a.usestatus']);
        }
        $model=new Cp();
        $model2=new  Cppt();
        $date=  $model->where('coupon_id',$id)->find();
        $xq=  $model2->alias('a')
            ->join('member m','a.member_id=m.member_id','right')
            ->where($where)->order("starttime desc")->paginate(10,false,['query'=>request()->param()]);
        $date['usenum'] = $model2->where(['coupon_id'=>$id,'usestatus'=>1])->count();

        $this->assign('data',$date);
        $this->assign('lie',$xq);
        $this->assign('where',$where);

        return $this->fetch();
    }

    //派发优惠券
    public function distributed(){
        $coupon_id=input('id');
        if (empty($coupon_id)) $this->error('参数错误');
        if($this->request->isPost()){
            $post=$this->request->post();
            $data=explode(',',$post['coupon_userange']);
            if(count($data) == 1){
                return ['code'=>2,'msg'=>'请选择派送客户'];
            }

            unset($data[0]);
            //该优惠券是否足够本次派发 coupon_quantity
            $coupon=Db::name('coupon')->where(['coupon_id'=>$coupon_id])->find();
            $coupon_num=$coupon['coupon_quantity'] - $coupon['coupon_alreadyreceived'];
            if(count($data) > $coupon_num && $coupon['num_types'] == 2 ){
                return ['code'=>2,'msg'=>'旅行红包数量不足'];
            }

            //已领优惠券
            $count_del=$coupon['coupon_alreadyreceived'] + count($data);

            $addcoupon=[];
            foreach ($data as $k){
                $coupondetails=[
                    'member_id'=>$k,
                    'coupon_id'=>$coupon_id,
                    'starttime'=>time(),
                    'usestatus'=>0
                ];
                $addcoupon[]=$coupondetails;
            }
            Db::startTrans();
            try{
                Db::name('coupondetails')->insertAll($addcoupon);
                Db::name('coupon')->where(['coupon_id'=>$coupon_id])->update(['coupon_alreadyreceived'=>$count_del]);
                Db::commit();
                return ['code'=>1,'msg'=>'派送成功'];
            }catch ( \Exception $e){
                Db::rollback();
                return ['code'=>2,'msg'=>'派送失败'];
            }


        }

        $member_list=Db::name('member')->field('member_id,member_nickname')->select();

        $this->assign('coupon_id',$coupon_id);
        $this->assign('members',$member_list);
        return $this->fetch();
    }

    //优惠券营销
    public function marketing(){
        $data=Db::name('coupon_marketing')->select();
        $this->assign('data',$data);
        return $this->fetch();
    }

    public function upmarket(){
        if($this->request->isPost()){
            $post = $this->request->post();
            //时间验证
            if($post['time_chose'] == 2){
                $post['starttime']=strtotime($post['starttime']);
                $post['endtime']=strtotime($post['endtime']);
                if($post['endtime'] < $post['starttime']){
                    $arr=[
                        'code'=>2,
                        'msg'=>'活动时间异常'
                    ];
                    return $arr;
                }
            }else{
                $post['starttime']=time();
                $post['endtime']=time();
            }

            $id = !empty($post['id']) ? $post['id'] : 0;
            unset($post['id']);

            if($id>0){//修改
                $res=Db::name('coupon_marketing')->where(['mk_id'=>$id])->update($post);
                if($res){
                    $arr=[
                        'code'=>1,
                        'msg'=>'修改成功'
                    ];
                    return $arr;
                }else{
                    $arr=[
                        'code'=>2,
                        'msg'=>'修改失败'
                    ];
                    return $arr;
                }
            }else{//新增
                $post['createtime'] = time();
                $res=Db::name('coupon_marketing')->insert($post);
                if($res){
                    $arr=[
                        'code'=>1,
                        'msg'=>'新增成功'
                    ];
                    return $arr;
                }else{
                    $arr=[
                        'code'=>2,
                        'msg'=>'新增失败'
                    ];
                    return $arr;
                }
            }
        }else{
            $id = input('id');
            $time=time();
            $w['coupon_status']=2;
            $w['etart_receivetime']=['<',$time];
            $w['end_receivetime']=['>',$time];

            //获取已领优惠券
            $res=Db::name('coupon_marketing')->where(['mk_id'=>$id])->find();
            $list=explode(',',$res['coupon_ids']);
            $data=Db::name('coupon')->where('coupon_id','IN',$list)->field('coupon_id,coupon_name')->select();

            //获取可领优惠券
            $coupon = Db::name('coupon')->where($w)->order("coupon_id desc")->select();
            $this->assign('coupon',$coupon);
            $this->assign('data',$res);
            $this->assign('list',$data);
            return $this->fetch();
        }
    }


}
